<template>
  <div>
    <el-row :gutter="24">
      <el-col :span="24">
        <!-- 卡片样式装载 -->
        <el-card shadow="always">
          <el-row :gutter="24">
            <el-col :span="12" :offset="6">
              <!-- 添加表单 -->
              <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="销售渠道" prop="channel">
                  <template>
                    <el-radio v-model="addForm.channel" :label=0>线下</el-radio>
                    <el-radio v-model="addForm.channel" :label=1>线上</el-radio>
                  </template>
                </el-form-item>
                <el-form-item label="销售方式" prop="saleType">
                  <template>
                    <el-radio v-model="addForm.saleType" :label=0>计件</el-radio>
                    <el-radio v-model="addForm.saleType" :label=1>计重</el-radio>
                  </template>
                </el-form-item>
                <el-form-item label="商品名" prop="productName">
                  <el-input v-model="addForm.productName"></el-input>
                </el-form-item>
                <el-form-item label="商品短标题" prop="productTitle">
                  <el-input v-model="addForm.productTitle"></el-input>
                </el-form-item>
                <el-form-item label="商品条码" prop="productCode">
                  <el-input v-model="addForm.productCode"></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="productType" style="text-align: left">
                  <el-cascader v-model="addForm.productType" :options="productTypes"
                               :props="{emitPath:false}"
                               :show-all-levels="false"></el-cascader>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="addForm.unit"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="productPrice">
                  <el-input v-model="addForm.productPrice"></el-input>
                </el-form-item>
                <el-form-item label="导购佣金" prop="delivery">
                  <el-switch v-model="addForm.delivery"></el-switch>
                </el-form-item>
                <el-form-item label="商品主图" prop="productImg">
                  <el-upload action="http://localhost:7000/admin/file/upload"
                             list-type="picture-card" name="file" :disabled="uploadDisabled"
                             :on-success="uploadSuccess" ref="upload" :file-list="imgList">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                      <img class="el-upload-list__item-thumbnail" :src="file.url" ref="prodImg">
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
                <el-form-item label="备注" prop="desc">
                  <el-input type="textarea" v-model="addForm.desc"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('addForm')" :loading="saveLoading">保存</el-button>
                  <el-button @click="resetForm('addForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-card>

      </el-col>
    </el-row>

  </div>
</template>

<script>
  import {get, post} from '@/api/http.js'

  export default {
    name: "productEdit",

    // 页面加载就执行
    mounted: function () {
      // 查询商品分类
      this.getProductType();

      let id = this.$store.state.productId;
      this.bizId = id;
      // ID存在就去查询数据回显
      if (id !== '') {
        get("/product/get/" + id, '')
          .then(res => {
            this.addForm = res.data;
            this.imgList = [{
              name: res.data.productImg,
              url: 'http://localhost:7000/admin/file/download?fileName=' + res.data.productImg
            }];
          })
          .catch(err => {})
          .finally(() => {});
      }
      this.$store.commit("setProductId", "");
    },

    data() {
      return {
        // 表单数据
        addForm: {
          channel: 0,
          saleType: 0,
          productName: '',
          productTitle: '',
          productCode: '',
          productPrice: '',
          productType: '',
          unit: '',
          delivery: false,
          desc: '',
          productImg: ''
        },
        // 表单 商品分类回显
        productTypeVo:[],

        // 表单校验
        rules: {
          productName: [
            {required: true, message: '请输入商品名', trigger: 'blur'},
            {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
          ],
          productCode: [
            {required: true, message: '请输入商品条码', trigger: 'blur'},
            {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
          ],
          productType: [
            {required: true, message: '请选择商品分类', trigger: 'change'}
          ],
          unit: [
            {required: true, message: '请输入单位', trigger: 'blur'},
            {min: 1, max: 3, message: '长度在 1 到 3 个字符', trigger: 'blur'}
          ],
          productPrice: [
            {required: true, message: '请输入商品价格', trigger: 'blur'},
            { type: 'number', message: '请输入准确商品价格'},
          ]
        },

        // 上传图片参数
        uploadDisabled: false,
        // 图片查看大图参数
        dialogImageUrl: '',
        dialogVisible: false,

        // 图片文件列表
        imgList: [],

        // 业务ID
        bizId: '',
        // 添加或修改时保存按钮加loading效果,防止表单重复提交
        saveLoading: false,

        // 商品分类
        productTypes: []
      };
    },
    methods: {

      // 获取商品分类数据
      getProductType(){
        post("/product/typeTree", '')
          .then(res => {
            this.productTypes = res.data;
          })
          .catch(err => {
          })
          .finally(() => {
          })
      },

      // 上传成功回调
      uploadSuccess(response, file, fileList) {
        this.addForm.productImg = response.data.fileName;
        this.uploadDisabled = true;
      },

      // 移除图片
      handleRemove(file) {
        this.uploadDisabled = false;
        let fileList = this.$refs.upload.uploadFiles;
        let index = fileList.findIndex(fileItem => {
          return fileItem.uid === file.uid
        });
        fileList.splice(index, 1);
      },

      // 查看大图
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          // 表单验证是否通过
          if (valid) {
            this.saveLoading = true;
            let uri = "";
            let msg = "";
            if (this.bizId === '') {
              uri = "/product/add";
              msg = "恭喜你，商品创建";
            } else {
              uri = "/product/update";
              msg = "恭喜你，商品修改";
            }
            // 发起请求
            post(uri, this.addForm)
              .then(res => {
                this.$message({
                  message: msg + '成功',
                  type: 'success'
                });
              })
              .catch(err => {
                this.$message({
                  message: msg + '失败',
                  type: 'error'
                });
              })
              .finally(() => {  // 请求响应之后在执行
                this.saveLoading = false;
                // 跳回列表页
                this.$router.replace({name: "ProductList"})
              })
          } else {
            return false;
          }
        });
      },
      // 重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped>

</style>
